package com.didispace.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    public static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

    public static HttpResponse post(String url, Map<String, String> params) {
        LOGGER.info("http请求开始：url = {},params:{}",url,params);

        String responseBody;
        PostMethod postMethod = new PostMethod(url);

        List<NameValuePair> data = new ArrayList<>();
        params.forEach((k,v) -> data.add(new NameValuePair(k,v)));

        postMethod.setRequestBody(data.toArray(new NameValuePair[data.size()]));
        HttpClient httpClient = new HttpClient();
        HttpResponse response = new HttpResponse();
        try {
            int statusCode = httpClient.executeMethod(postMethod);

            LOGGER.info("http请求响应 code:{}",statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode==HttpStatus.SC_PARTIAL_CONTENT) {
                responseBody = postMethod.getResponseBodyAsString();
                LOGGER.info("http请求响应内容:code:{},内容:{}" ,statusCode,responseBody);
                response.setData(responseBody);
                response.setStatus(Boolean.TRUE);
            }else{
                response.setStatus(Boolean.FALSE);
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        return response;
    }

}
